<script setup>
import { ref } from 'vue'
import api from '../api'  // 导入 axios

const file = ref(null)
const markdownText = ref('')
const loading = ref(false)
const errorMsg = ref('')

const handleFileChange = (event) => {
  file.value = event.target.files[0]
  errorMsg.value = ''
}

const copyToClipboard = () => {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(markdownText.value)
        .then(() => {
          // 复制成功后的提示，可以根据需要进行修改
          alert('已复制到剪切板！')
        })
        .catch(err => {
          console.error('复制失败:', err)
          alert('复制失败，请手动复制。')
        })
  } else {
    // 兼容性处理
    alert('您的浏览器不支持 Clipboard API，请手动复制')
  }
}

const convertFile = async () => {
  if (!file.value) {
    errorMsg.value = '请先选择文件！'
    return
  }

  loading.value = true
  errorMsg.value = ''
  markdownText.value = ''

  const formData = new FormData()
  formData.append('file', file.value)

  try {
    const response = await api.post('/uploadfile', formData) // 使用 api 实例
    markdownText.value = response.data.markdown_content // 假设后端返回的数据结构是 { markdown: "..." }
  } catch (error) {
    console.error('转换失败', error)
    // axios 会自动处理非 2xx 状态码，并抛出错误
    // 我们可以通过 error.response 来访问更详细的错误信息
    errorMsg.value = error.response?.data?.message || '转换失败，请检查文件格式或稍后重试。'
  } finally {
    loading.value = false
  }
}
</script>

<template>
  <v-container class="converter-container py-8">
    <v-row justify="center">
      <v-col cols="12" sm="10" md="8" lg="7">
        <v-card class="converter-card" elevation="3">
          <!-- 标题区域 -->
          <v-card-title class="text-h4 font-weight-bold text-center py-6 primary--text">
            文档转换器
            <v-tooltip location="right">
              <template v-slot:activator="{ props }">
                <v-icon
                  v-bind="props"
                  icon="mdi-help-circle-outline"
                  class="ml-2"
                  size="small"
                >
                </v-icon>
              </template>
              <span>支持 Word 和 Excel 文件转换为 Markdown 格式</span>
            </v-tooltip>
          </v-card-title>

          <v-divider></v-divider>

          <v-card-text class="pa-6">
            <div class="d-flex flex-column gap-6">
              <!-- 文件上传区域 -->
              <div class="file-upload-section">
                <v-file-input
                  v-model="file"
                  @change="handleFileChange"
                  accept=".doc,.docx,.xls,.xlsx"
                  :error-messages="errorMsg"
                  variant="outlined"
                  label="选择 Word/Excel 文件"
                  prepend-icon="mdi-file-document-outline"
                  density="comfortable"
                  :error="!!errorMsg"
                  class="upload-input"
                  persistent-hint
                  hint="支持的格式：.docx, .xlsx"
                ></v-file-input>
              </div>

              <!-- 转换按钮 -->
              <!-- 转换按钮 -->
              <div class="d-flex justify-center">
                <v-btn
                    color="primary"
                    size="x-large"
                    :loading="loading"
                    @click="convertFile"
                    min-width="200"
                    class="convert-btn"
                    :disabled="!file"
                    style="margin-bottom: 20px; text-transform: none;"
                >
                  <v-icon start class="mr-2">mdi-swap-horizontal</v-icon>

                  {{ loading ? '正在转换...' : '转换为 Markdown' }}
                </v-btn>
              </div>

              <!-- Markdown 预览区域 -->
              <div class="markdown-preview-section">
                <v-sheet
                    class="rounded-lg pa-4"
                    color="grey-lighten-4"
                    v-if="markdownText || loading"
                >
                  <div class="d-flex justify-space-between align-center mb-2">
                    <span class="text-subtitle-1 font-weight-medium">Markdown 预览</span>
                    <v-btn
                        v-if="markdownText && !loading"
                        color="success"
                        variant="tonal"
                        density="comfortable"
                        prepend-icon="mdi-content-copy"
                        @click="copyToClipboard"
                        style="text-transform: none;"
                    >复制内容
                    </v-btn>
                  </div>
                  <v-textarea
                      v-model="markdownText"
                      placeholder="转换后的内容将显示在这里..."
                      variant="outlined"
                      :readonly="true"
                      rows="10"
                      hide-details
                      class="markdown-output"
                      bg-color="white"
                      density="comfortable"
                  ></v-textarea>
                </v-sheet>
              </div>
            </div>
          </v-card-text>
        </v-card>
      </v-col>
    </v-row>
  </v-container>
</template>

<style scoped>
.converter-card {
  border-radius: 16px;
  transition: all 0.3s ease;
}

.converter-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.1) !important;
}

.file-upload-section {
  transition: all 0.3s ease;
}

.convert-btn {
  transition: all 0.3s ease;
}

.convert-btn:not(:disabled):hover {
  transform: scale(1.02);
}

.markdown-output {
  font-family: 'Courier New', Courier, monospace;
}

.markdown-preview-section {
  transition: all 0.3s ease;
}

:deep(.v-field) {
  border-radius: 8px;
}

:deep(.v-btn) {
  border-radius: 8px;
}
</style>